<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽健身积分管理</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/badge.css') }}">

    <style>
        #cusNameResultList{
            display: none;
            border-radius:3px;
            border:1px solid #183b6c;
            font-size: 13px;
            line-height: 34px;
            position: absolute;
            color:rgb(47, 54, 100);
            padding-left:10px;
            padding-right: 10px;
            /* width:180px; */
            top:98px;
            left:150px;
            background-color: rgb(245, 249, 254);
            z-index: 1;
            list-style-position: inside;
        }

        .card{
            display: flex;
            flex-direction: column;            
            width:400px;
            height: 300px;       
            border: #D8C4A3 solid 1px;
            border-radius: 12px;  
            background-color: #F8F4E6;
            box-shadow: 0 4px 12px rgba(200, 180, 140, 0.15);
            padding: 20px;
            font-family: 'Microsoft YaHei', sans-serif;
            align-items: center;
            justify-content: center;
            margin:20px 0;
            
        }

        .card-name {
            font-size: 24px;
            font-weight: bold;
            color: #8B6B3D;
            margin-bottom: 15px;
            text-align: center;
        }

        .stage {
            font-size: 22px;
            color: #A67C52;
            margin-bottom: 10px;
            text-align: center;
        }

        .offset-amount {
            font-size: 16px;
            color: #B8A089;
            margin-bottom: 15px;
            text-align: center;
            font-style: italic;
        }

        #badge {
            text-align: center;
            margin-bottom: 20px;
            font-size: 18px;
            font-weight: bold;
            width: 100% !important;
            display: block !important;
        }
        
        /* .badge div {
            display: inline-block;
            padding: 8px 16px;
            border-radius: 20px;
            text-align: center;
        } */

        #rewards {
            font-size: 24px;
            font-weight: bold;
            color: #D4A76A;
            text-align: center;
            margin-top: 20px;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
        }

        #remainRewards {
            font-size: 14px;
            color: #A67C52;
            text-align: center;
            margin-top: 10px;
        }

        #starStandard{
            display: flex;
            flex-direction: column;            
            width:400px;    
            border: #faecd5 solid 1px;
            border-radius: 12px;  
            background-color: #fffffd;
            box-shadow: 0 4px 12px rgba(200, 180, 140, 0.15);
            padding: 20px;
            font-family: 'Microsoft YaHei', sans-serif;
            font-size:22px;
            align-items: center;
            justify-content: center;
            margin:20px 0;
            line-height: 48px;
        }
        .star-standard-content{
            margin: 20px 0;
        }

        /* 响应式布局 */
        @media (max-width: 768px) {
            .card {
                width: 90% !important;
                height: auto;
                aspect-ratio: 4/3;
                margin: 30px auto;
                padding: 15px;
            }
            
            #starStandard {
                width: 90% !important;
                height: auto;
                margin: 10px auto;
                padding: 15px;
                font-size: 18px;
                line-height: 36px;
            }
            
            .card-name {
                font-size: 20px;
            }
            
            .stage {
                font-size: 18px;
            }
            
            #rewards {
                font-size: 20px;
            }
            
            .star-standard-content {
                margin: 15px 0;
            }
        }

       

    </style>
</head>
<body>
    {% include 'show_ins_info.html' %}
    <div id="inputContents">
        <h3>会员编码及姓名：</h3>
        
        <input type="text" id="cusNameInput" style="width: 120px;" oninput="handleInput();">
        <ul id="cusNameResultList"></ul>
        <hr>
        <div>
            <div id="card" class="card">               
                <div id="cardCusName" class="card-name"></div>
                <div id="stage" class="stage"></div>
                <div id="offsetAmount" class="offset-amount"></div>
                <div id="badge"></div>
                <div id="rewards"></div>
                <div id="remainRewards"></div>
            </div>

            <div id="starStandard">
                <div class="star-standard-content">
                    <div style="color:#8f7459;font-weight: bold;">积分达1300分</div>
                    <div style="color:#f77f48;font-weight: bold;">★ 四星会员 | 知行合一勋章</div>
                </div>
                <div class="star-standard-content">
                    <div style="color:#8f7459;font-weight: bold;">积分达950分</div>
                    <div style="color:#f77f48;font-weight: bold;">★ 三星会员 | 身体力行勋章</div>
                </div>
                <div class="star-standard-content">
                    <div style="color:#8f7459;font-weight: bold;">积分达570分</div>
                    <div style="color:#f77f48;font-weight: bold;">★ 二星会员 | 渐入佳境勋章</div>
                </div>
                <div class="star-standard-content">
                    <div style="color:#8f7459;font-weight: bold;">初次购课即为</div>
                    <div style="color:#f77f48;font-weight: bold;">★ 一星会员 | 心动行动勋章</div>
                </div>
            </div>
        </div>

        
        
        <!-- <h1>积分操作</h1>
        <select id="rewardAction">
            <option value="add">增加积分</option>
            <option value="deduct">扣除积分</option>
            <option value="query">查询积分</option>
        </select>

        <h3>积分数量</h3>
        <input type="number" id="rewardPoints" step="1" min="0">

        <h3>操作日期</h3>
        <input type="date" id="dateInput">

        <h3>操作原因</h3>
        <input type="text" id="reason" style="width: 190px;">

        <h3>操作人</h3>
        <select id="operator">
            <option value="">请选择</option>
        </select>

        <div class="inline2" id="status"></div> 
    </div>

    <div><button id='submitBtn' style="margin-right:5px;">提交</button></div>-->

    <script src="../static/js/moment.min.js"></script>
    <script src="../static/js/common.js"></script>
    <script>
        // JavaScript部分留空
        // 这里将包含积分管理的相关逻辑
        let cusList;
        let cusStageConfig;
        let cusRewards;
        
        document.addEventListener("DOMContentLoaded", function() {   
            // loginCheck();
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insName=insInfo['sessionInsName'];
            insId=insInfo['sessionInsId'];
            insRole=insInfo['sessionInsRole'];

            document.getElementById('card').style.display='none';
            document.getElementById(`offsetAmount`).innerHTML='';

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                // console.log('cus list:',data);
                cusList=data;
                  })
                .catch(error => console.error('Error:', error));

                fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('ins list:',data);


                 })
                .catch(error => console.error('Error:', error));

            //获取积分配置
            getCusStageConfig();
        });


       async function handleInput(){
            // 获取输入框中的值
            const searchTerm = document.getElementById("cusNameInput").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusNameResultList")

            //隐藏结果
            document.getElementById('card').style.display='none';
            document.getElementById(`offsetAmount`).innerHTML='';


            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";

            }

            // 遍历给定的数组，进行模糊匹配
            cusList.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.textContent = name;

                    // 添加点击事件监听器
                    listItem.addEventListener("click", async function() {
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("cusNameInput").value = name;

                        resultList.style.display = "none";
                        resultList.innerHTML = ""       
                        
                        try {
                            // 使用 await 获取返回值
                            const rewardsInfo = await getCusRewards(name);
                            console.log('客户积分信息：',rewardsInfo);
                            showCusRewards(rewardsInfo[0],name)

                            //显示积分结果
                            document.getElementById('card').style.display='flex';
                            

                        } catch (error) {
                            console.error('获取会员积分错误：', error);
                            cusTotalAmount = 0;
                        }

                        // get_cus_continue_buy();
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                    
                }else{
           

                }
            });
        
            // resultList.classList.add("cus-list-result");
            // resultList.style.top='138px';
            // resultList.style.left='214px';
            
        } 

    function showCusRewards(rewardsInfo,name){
        const totalAmount=parseFloat(rewardsInfo.total_real_pay);   
        const ranges = Object.keys(cusStageConfig);
        let range = null;
        for (const rangeKey of ranges) {
        const [min, max] = rangeKey.split('-').map(Number);
        if (totalAmount >= min && totalAmount < max) {
            range = cusStageConfig[rangeKey];
            console.log('所在的range：',range);
            break;
        }
        }

        // 根据会员等级显示相应的勋章
        let badgeClass = '';
        let badgeText = range.name;
        
        switch(range.name) {
            case '心动行动':
                badgeClass = 'badge badge-bronze';
                break;
            case '渐入佳境':
                badgeClass = 'badge badge-silver';
                break;
            case '身体力行':
                badgeClass = 'badge badge-gold';
                break;
            case '知行合一':
                badgeClass = 'badge badge-platinum badge-glow';
                break;
            default:
                badgeClass = 'badge badge-bronze';
        }

        document.getElementById(`stage`).innerHTML=`${range.star}`;
        if(range.star && ['二星会员','三星会员','四星会员'].includes(range.star)){
            document.getElementById(`stage`).innerHTML=`<div><div>${range.star}</div><div style="color:orange;">购课即享优惠</div></div>`;
            document.getElementById(`offsetAmount`).innerHTML=`<div>每次单笔实际消费满${range.offset_limit}元立减${range.offset_amount}元</div>`;
        }
        document.getElementById(`cardCusName`).innerHTML=`${name.slice(7,)} ${rewardsInfo.sex==='男'?'先生':'女士'}`;
        document.getElementById(`badge`).innerHTML=`<div class="${badgeClass}" >${badgeText}勋章</div>`;
        document.getElementById(`rewards`).innerHTML=`积分 ${rewardsInfo.reward_points} `;
    }

    function getCusStageConfig(){
            fetch('/get_cus_stage_config', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {                
                cusStageConfig=data.stage_config;
                console.log('cusStageConfig list:',cusStageConfig);
                  })
                .catch(error => console.error('Error:', error)); 

        }



    function getCusRewards(name){
        return fetch(`/get_cus_rewards?cus_id=${encodeURIComponent(name.slice(0,7))}`)
                .then(response => response.json())
                .then(data => {
                    if(data.res==='ok'){
                        // console.log('get cus rewards:',data.data);
                        return data.data;
                    }else{
                        throw new Error(data.msg || '获取积分信息失败');
                    }
                  })
                .catch(error => {
                    console.error('Error:', error);
                    throw error;
                });

         
        
    }

    </script>
</body>
</html>
